<template>
    <div class="contact_apply">
        <DefaultHeader :title="titles[Number.parseInt(route.params.type[0])]"></DefaultHeader>
        <div>
            <UserItem v-for="(item, index) in users" :key="index" :user="item" v-if="isNewUser">

                <template #action>
                    <div>
                        <div v-if="item.status == 0">

                            <el-button class="action_btn" @click="requestHandle(item, 1)">同意</el-button>
                            <el-button class="action_btn" @click="requestHandle(item, 2)">拒绝</el-button>

                        </div>
                        <div v-else-if="item.status == 1">
                            已同意
                        </div>

                        <div v-else-if="item.status == 2">
                            已拒绝
                        </div>
                    </div>
                </template>

            </UserItem>

            <div v-else>
                群聊
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { friendRequestHandle, requestList } from '@/api/friendRequest';
import DefaultHeader from '@/components/header/DefaultHeader.vue';
import UserItem, { type FriendRequestItem } from '@/components/UserItem.vue';
import { useMessageStore } from '@/stores/messageStore';
import { ElMessage } from 'element-plus';
import { computed, ref } from 'vue';
import { useRoute } from 'vue-router';
const route = useRoute();
const titles = ['新好友', '群通知'];

const users = ref<Array<FriendRequestItem>>([]);

const isNewUser = computed(() => Number.parseInt(route.params.type[0]) == 0 ? true : false);

const requestHandle = async (item: FriendRequestItem, status: number) => {
    try {
        const result = await friendRequestHandle(item.userId, status);
        if (result.code === 1) {
            ElMessage.success(`已${status == 1 ? '同意' : '拒绝'}`);
            item.status = status;
            //同意了, 创建聊天界面
            if (status == 1) {
                const messageStore = useMessageStore();
                messageStore.messageList.push({
                    nick: item.nick,
                    avatar: item.avatar,
                    content: "你们已成为好友~",
                    time: "现在",
                    unreadCount: 1,
                });
            }
        }
    } catch (e) {
        console.log(e);
    }
}

const requests = async () => {
    try {
        const result = await requestList();
        if (result.code === 1) {
            users.value = result.data
        }
    } catch (e) {
        console.log(e);
    }
}

const init = () => {
    requests();
}

init();
</script>

<style lang="scss" scoped>
.contact_apply {
    height: 100%;
    overflow-y: aotu;
}

.action_btn {
    height: 30px;
    background-color: rgb(255, 197, 197)
}
</style>
